/*** Eclipse Class Decompiler plugin, copyright (c) 2012 Chao Chen (cnfree2000@hotmail.com) ***/

package com.openbravo.pos.forms;

import com.openbravo.basic.BasicException;
import com.openbravo.data.loader.*;
import com.openbravo.data.model.Field;
import com.openbravo.data.model.Row;
import com.openbravo.format.Formats;
import com.openbravo.pos.customers.CustomerInfoExt;
import com.openbravo.pos.inventory.*;
import com.openbravo.pos.mant.FloorsInfo;
import com.openbravo.pos.payment.PaymentInfo;
import com.openbravo.pos.payment.PaymentInfoTicket;
import com.openbravo.pos.ticket.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.*;

public class DataLogicSales extends BeanFactoryDataSingle {
	protected static class CustomerExtRead implements SerializerRead {

		public Object readValues(DataRead dr) throws BasicException {
			CustomerInfoExt c = new CustomerInfoExt(dr.getString(1));
			c.setTaxid(dr.getString(2));
			c.setSearchkey(dr.getString(3));
			c.setName(dr.getString(4));
			c.setCard(dr.getString(5));
			c.setTaxCustomerID(dr.getString(6));
			c.setNotes(dr.getString(7));
			c.setMaxdebt(dr.getDouble(8));
			c.setVisible(dr.getBoolean(9).booleanValue());
			c.setCurdate(dr.getTimestamp(10));
			c.setCurdebt(dr.getDouble(11));
			c.setFirstname(dr.getString(12));
			c.setLastname(dr.getString(13));
			c.setEmail(dr.getString(14));
			c.setPhone(dr.getString(15));
			c.setPhone2(dr.getString(16));
			c.setFax(dr.getString(17));
			c.setAddress(dr.getString(18));
			c.setAddress2(dr.getString(19));
			c.setPostal(dr.getString(20));
			c.setCity(dr.getString(21));
			c.setRegion(dr.getString(22));
			c.setCountry(dr.getString(23));
			return c;
		}

	}

	protected Session s;
	protected Datas auxiliarDatas[];
	protected Datas stockdiaryDatas[];
	protected Datas paymenttabledatas[];
	protected Datas stockdatas[];
	protected Row productsRow;

	public DataLogicSales() {
		stockdiaryDatas = (new Datas[] { Datas.STRING, Datas.TIMESTAMP,
				Datas.INT, Datas.STRING, Datas.STRING, Datas.STRING,
				Datas.DOUBLE, Datas.DOUBLE });
		paymenttabledatas = (new Datas[] { Datas.STRING, Datas.STRING,
				Datas.TIMESTAMP, Datas.STRING, Datas.STRING, Datas.DOUBLE });
		stockdatas = (new Datas[] { Datas.STRING, Datas.STRING, Datas.STRING,
				Datas.DOUBLE, Datas.DOUBLE, Datas.DOUBLE });
		auxiliarDatas = (new Datas[] { Datas.STRING, Datas.STRING,
				Datas.STRING, Datas.STRING, Datas.STRING, Datas.STRING });
		productsRow = new Row(new Field[] {
				new Field("ID", Datas.STRING, Formats.STRING),
				new Field(AppLocal.getIntString("label.prodref"), Datas.STRING,
						Formats.STRING, true, true, true),
				new Field(AppLocal.getIntString("label.prodbarcode"),
						Datas.STRING, Formats.STRING, false, true, true),
				new Field(AppLocal.getIntString("label.prodname"),
						Datas.STRING, Formats.STRING, true, true, true),
				new Field("ISCOM", Datas.BOOLEAN, Formats.BOOLEAN),
				new Field("ISSCALE", Datas.BOOLEAN, Formats.BOOLEAN),
				new Field(AppLocal.getIntString("label.prodpricebuy"),
						Datas.DOUBLE, Formats.CURRENCY, false, true, true),
				new Field(AppLocal.getIntString("label.prodpricesell"),
						Datas.DOUBLE, Formats.CURRENCY, false, true, true),
				new Field(AppLocal.getIntString("label.prodcategory"),
						Datas.STRING, Formats.STRING, false, false, true),
				new Field(AppLocal.getIntString("label.taxcategory"),
						Datas.STRING, Formats.STRING, false, false, true),
				new Field(AppLocal.getIntString("label.attributeset"),
						Datas.STRING, Formats.STRING, false, false, true),
				new Field("IMAGE", Datas.IMAGE, Formats.NULL),
				new Field("STOCKCOST", Datas.DOUBLE, Formats.CURRENCY),
				new Field("STOCKVOLUME", Datas.DOUBLE, Formats.DOUBLE),
				new Field("ISCATALOG", Datas.BOOLEAN, Formats.BOOLEAN),
				new Field("CATORDER", Datas.INT, Formats.INT),
				new Field("PROPERTIES", Datas.BYTES, Formats.NULL) });
	}

	public void init(Session s) {
		this.s = s;
	}

	public final Row getProductsRow() {
		return productsRow;
	}

	public final ProductInfoExt getProductInfo(String id) throws BasicException {
		return (ProductInfoExt) (new PreparedSentence(
				s,
				"SELECT ID, REFERENCE, CODE, NAME, ISCOM, ISSCALE, PRICEBUY, PRICESELL, TAXCAT, CATEGORY, ATTRIBUTESET_ID, IMAGE, ATTRIBUTES FROM PRODUCTS WHERE ID = ?",
				SerializerWriteString.INSTANCE, ProductInfoExt
						.getSerializerRead())).find(id);
	}

	public final ProductInfoExt getProductInfoByCode(String sCode)
			throws BasicException {
		return (ProductInfoExt) (new PreparedSentence(
				s,
				"SELECT ID, REFERENCE, CODE, NAME, ISCOM, ISSCALE, PRICEBUY, PRICESELL, TAXCAT, CATEGORY, ATTRIBUTESET_ID, IMAGE, ATTRIBUTES FROM PRODUCTS WHERE CODE = ?",
				SerializerWriteString.INSTANCE, ProductInfoExt
						.getSerializerRead())).find(sCode);
	}

	public final ProductInfoExt getProductInfoByReference(String sReference)
			throws BasicException {
		return (ProductInfoExt) (new PreparedSentence(
				s,
				"SELECT ID, REFERENCE, CODE, NAME, ISCOM, ISSCALE, PRICEBUY, PRICESELL, TAXCAT, CATEGORY, ATTRIBUTESET_ID, IMAGE, ATTRIBUTES FROM PRODUCTS WHERE REFERENCE = ?",
				SerializerWriteString.INSTANCE, ProductInfoExt
						.getSerializerRead())).find(sReference);
	}

	public final List getRootCategories() throws BasicException {
		return (new PreparedSentence(
				s,
				"SELECT ID, NAME, IMAGE FROM CATEGORIES WHERE PARENTID IS NULL ORDER BY NAME",
				null, CategoryInfo.getSerializerRead())).list();
	}

	public final List getSubcategories(String category) throws BasicException {
		return (new PreparedSentence(
				s,
				"SELECT ID, NAME, IMAGE FROM CATEGORIES WHERE PARENTID = ? ORDER BY NAME",
				SerializerWriteString.INSTANCE, CategoryInfo
						.getSerializerRead())).list(category);
	}

	public List getProductCatalog(String category) throws BasicException {
		return (new PreparedSentence(
				s,
				"SELECT P.ID, P.REFERENCE, P.CODE, P.NAME, P.ISCOM, P.ISSCALE, P.PRICEBUY, P.PRICESELL, P.TAXCAT, P.CATEGORY, P.ATTRIBUTESET_ID, P.IMAGE, P.ATTRIBUTES FROM PRODUCTS P, PRODUCTS_CAT O WHERE P.ID = O.PRODUCT AND P.CATEGORY = ? ORDER BY O.CATORDER, P.NAME",
				SerializerWriteString.INSTANCE, ProductInfoExt
						.getSerializerRead())).list(category);
	}

	public List getProductComments(String id) throws BasicException {
		return (new PreparedSentence(
				s,
				(new StringBuilder())
						.append("SELECT P.ID, P.REFERENCE, P.CODE, P.NAME, P.ISCOM, P.ISSCALE, P.PRICEBUY, P.PRICESELL, P.TAXCAT, P.CATEGORY, P.ATTRIBUTESET_ID, P.IMAGE, P.ATTRIBUTES FROM PRODUCTS P, PRODUCTS_CAT O, PRODUCTS_COM M WHERE P.ID = O.PRODUCT AND P.ID = M.PRODUCT2 AND M.PRODUCT = ? AND P.ISCOM = ")
						.append(s.DB.TRUE()).append(" ")
						.append("ORDER BY O.CATORDER, P.NAME").toString(),
				SerializerWriteString.INSTANCE,
				ProductInfoExt.getSerializerRead())).list(id);
	}

	public final SentenceList getProductList() {
		return new StaticSentence(
				s,
				new QBFBuilder(
						"SELECT ID, REFERENCE, CODE, NAME, ISCOM, ISSCALE, PRICEBUY, PRICESELL, TAXCAT, CATEGORY, ATTRIBUTESET_ID, IMAGE, ATTRIBUTES FROM PRODUCTS WHERE ?(QBF_FILTER) ORDER BY REFERENCE",
						new String[] { "NAME", "PRICEBUY", "PRICESELL",
								"CATEGORY", "CODE" }),
				new SerializerWriteBasic(new Datas[] { Datas.OBJECT,
						Datas.STRING, Datas.OBJECT, Datas.DOUBLE, Datas.OBJECT,
						Datas.DOUBLE, Datas.OBJECT, Datas.STRING, Datas.OBJECT,
						Datas.STRING }), ProductInfoExt.getSerializerRead());
	}

	public SentenceList getProductListNormal() {
		return new StaticSentence(
				s,
				new QBFBuilder(
						(new StringBuilder())
								.append("SELECT ID, REFERENCE, CODE, NAME, ISCOM, ISSCALE, PRICEBUY, PRICESELL, TAXCAT, CATEGORY, ATTRIBUTESET_ID, IMAGE, ATTRIBUTES FROM PRODUCTS WHERE ISCOM = ")
								.append(s.DB.FALSE())
								.append(" AND ?(QBF_FILTER) ORDER BY REFERENCE")
								.toString(), new String[] { "NAME", "PRICEBUY",
								"PRICESELL", "CATEGORY", "CODE" }),
				new SerializerWriteBasic(new Datas[] { Datas.OBJECT,
						Datas.STRING, Datas.OBJECT, Datas.DOUBLE, Datas.OBJECT,
						Datas.DOUBLE, Datas.OBJECT, Datas.STRING, Datas.OBJECT,
						Datas.STRING }), ProductInfoExt.getSerializerRead());
	}

	public SentenceList getProductListAuxiliar() {
		return new StaticSentence(
				s,
				new QBFBuilder(
						(new StringBuilder())
								.append("SELECT ID, REFERENCE, CODE, NAME, ISCOM, ISSCALE, PRICEBUY, PRICESELL, TAXCAT, CATEGORY, ATTRIBUTESET_ID, IMAGE, ATTRIBUTES FROM PRODUCTS WHERE ISCOM = ")
								.append(s.DB.TRUE())
								.append(" AND ?(QBF_FILTER) ORDER BY REFERENCE")
								.toString(), new String[] { "NAME", "PRICEBUY",
								"PRICESELL", "CATEGORY", "CODE" }),
				new SerializerWriteBasic(new Datas[] { Datas.OBJECT,
						Datas.STRING, Datas.OBJECT, Datas.DOUBLE, Datas.OBJECT,
						Datas.DOUBLE, Datas.OBJECT, Datas.STRING, Datas.OBJECT,
						Datas.STRING }), ProductInfoExt.getSerializerRead());
	}

	public SentenceList getTicketsList() {
		return new StaticSentence(
				s,
				new QBFBuilder(
						"SELECT T.TICKETID, T.TICKETTYPE, R.DATENEW, P.NAME, C.NAME, SUM(PM.TOTAL) FROM RECEIPTS R JOIN TICKETS T ON R.ID = T.ID LEFT OUTER JOIN PAYMENTS PM ON R.ID = PM.RECEIPT LEFT OUTER JOIN CUSTOMERS C ON C.ID = T.CUSTOMER LEFT OUTER JOIN PEOPLE P ON T.PERSON = P.ID WHERE ?(QBF_FILTER) GROUP BY T.ID, T.TICKETID, T.TICKETTYPE, R.DATENEW, P.NAME, C.NAME ORDER BY R.DATENEW DESC, T.TICKETID",
						new String[] { "T.TICKETID", "T.TICKETTYPE",
								"PM.TOTAL", "R.DATENEW", "R.DATENEW", "P.NAME",
								"C.NAME" }), new SerializerWriteBasic(
						new Datas[] { Datas.OBJECT, Datas.INT, Datas.OBJECT,
								Datas.INT, Datas.OBJECT, Datas.DOUBLE,
								Datas.OBJECT, Datas.TIMESTAMP, Datas.OBJECT,
								Datas.TIMESTAMP, Datas.OBJECT, Datas.STRING,
								Datas.OBJECT, Datas.STRING }),
				new SerializerReadClass(FindTicketsInfo.class));
	}

	public final SentenceList getUserList() {
		return new StaticSentence(s,
				"SELECT ID, NAME FROM PEOPLE ORDER BY NAME", null,
				new SerializerRead() {

				//	final DataLogicSales this$0;

					public Object readValues(DataRead dr) throws BasicException {
						return new TaxCategoryInfo(dr.getString(1), dr
								.getString(2));
					}

//					{
//						this$0 = DataLogicSales.this;
//						super();
//					}
				});
	}

	public final SentenceList getTaxList() {
		return new StaticSentence(
				s,
				"SELECT ID, NAME, CATEGORY, VALIDFROM, CUSTCATEGORY, PARENTID, RATE, RATECASCADE, RATEORDER FROM TAXES ORDER BY NAME",
				null, new SerializerRead() {

				//	final DataLogicSales this$0;

					public Object readValues(DataRead dr) throws BasicException {
						return new TaxInfo(dr.getString(1), dr.getString(2), dr
								.getString(3), dr.getTimestamp(4), dr
								.getString(5), dr.getString(6), dr.getDouble(7)
								.doubleValue(),
								dr.getBoolean(8).booleanValue(), dr.getInt(9));
					}
//
//					{
//						this$0 = DataLogicSales.this;
//						super();
//					}
				});
	}

	public final SentenceList getCategoriesList() {
		return new StaticSentence(s,
				"SELECT ID, NAME, IMAGE FROM CATEGORIES ORDER BY NAME", null,
				CategoryInfo.getSerializerRead());
	}

	public final SentenceList getTaxCustCategoriesList() {
		return new StaticSentence(s,
				"SELECT ID, NAME FROM TAXCUSTCATEGORIES ORDER BY NAME", null,
				new SerializerRead() {

				///	final DataLogicSales this$0;

					public Object readValues(DataRead dr) throws BasicException {
						return new TaxCustCategoryInfo(dr.getString(1), dr
								.getString(2));
					}

//					{
//						this$0 = DataLogicSales.this;
//						super();
//					}
				});
	}

	public final SentenceList getTaxCategoriesList() {
		return new StaticSentence(s,
				"SELECT ID, NAME FROM TAXCATEGORIES ORDER BY NAME", null,
				new SerializerRead() {

				//	final DataLogicSales this$0;

					public Object readValues(DataRead dr) throws BasicException {
						return new TaxCategoryInfo(dr.getString(1), dr
								.getString(2));
					}

//					{
//						this$0 = DataLogicSales.this;
//						super();
//					}
				});
	}

	public final SentenceList getAttributeSetList() {
		return new StaticSentence(s,
				"SELECT ID, NAME FROM ATTRIBUTESET ORDER BY NAME", null,
				new SerializerRead() {

				//	final DataLogicSales this$0;

					public Object readValues(DataRead dr) throws BasicException {
						return new AttributeSetInfo(dr.getString(1), dr
								.getString(2));
					}

//					{
//						this$0 = DataLogicSales.this;
//						super();
//					}
				});
	}

	public final SentenceList getLocationsList() {
		return new StaticSentence(s,
				"SELECT ID, NAME, ADDRESS FROM LOCATIONS ORDER BY NAME", null,
				new SerializerReadClass(LocationInfo.class ));
	}

	public final SentenceList getFloorsList() {
		return new StaticSentence(s,
				"SELECT ID, NAME FROM FLOORS ORDER BY NAME", null,
				new SerializerReadClass(  FloorsInfo.class));
	}

	public CustomerInfoExt findCustomerExt(String card) throws BasicException {
		return (CustomerInfoExt) (new PreparedSentence(
				s,
				(new StringBuilder())
						.append("SELECT ID, TAXID, SEARCHKEY, NAME, CARD, TAXCATEGORY, NOTES, MAXDEBT, VISIBLE, CURDATE, CURDEBT, FIRSTNAME, LASTNAME, EMAIL, PHONE, PHONE2, FAX, ADDRESS, ADDRESS2, POSTAL, CITY, REGION, COUNTRY FROM CUSTOMERS WHERE CARD = ? AND VISIBLE = ")
						.append(s.DB.TRUE()).toString(),
				SerializerWriteString.INSTANCE, new CustomerExtRead()))
				.find(card);
	}

	public CustomerInfoExt loadCustomerExt(String id) throws BasicException {
		return (CustomerInfoExt) (new PreparedSentence(
				s,
				"SELECT ID, TAXID, SEARCHKEY, NAME, CARD, TAXCATEGORY, NOTES, MAXDEBT, VISIBLE, CURDATE, CURDEBT, FIRSTNAME, LASTNAME, EMAIL, PHONE, PHONE2, FAX, ADDRESS, ADDRESS2, POSTAL, CITY, REGION, COUNTRY FROM CUSTOMERS WHERE ID = ?",
				SerializerWriteString.INSTANCE, new CustomerExtRead()))
				.find(id);
	}

	public final boolean isCashActive(String id) throws BasicException {
		return (new PreparedSentence(
				s,
				"SELECT MONEY FROM CLOSEDCASH WHERE DATEEND IS NULL AND MONEY = ?",
				SerializerWriteString.INSTANCE, SerializerReadString.INSTANCE))
				.find(id) != null;
	}

	public final TicketInfo loadTicket(final int tickettype, final int ticketid)
			throws BasicException {
		TicketInfo ticket = (TicketInfo) (new PreparedSentence(
				s,
				"SELECT T.ID, T.TICKETTYPE, T.TICKETID, R.DATENEW, R.MONEY, R.ATTRIBUTES, P.ID, P.NAME, T.CUSTOMER FROM RECEIPTS R JOIN TICKETS T ON R.ID = T.ID LEFT OUTER JOIN PEOPLE P ON T.PERSON = P.ID WHERE T.TICKETTYPE = ? AND T.TICKETID = ?",
				SerializerWriteParams.INSTANCE, new SerializerReadClass(  TicketInfo.class)))
				.find(new DataParams() {

//					final int val$tickettype;
//					final int val$ticketid;
//					final DataLogicSales this$0;

					public void writeValues() throws BasicException {
						setInt(1, Integer.valueOf(tickettype));
						setInt(2, Integer.valueOf(ticketid));
					}

//					{
//						this$0 = DataLogicSales.this;
//						tickettype = i;
//						ticketid = j;
//						super();
//					}
				});
		if (ticket != null) {
			String customerid = ticket.getCustomerId();
			ticket.setCustomer(customerid != null ? loadCustomerExt(customerid)
					: null);
			ticket.setLines((new PreparedSentence(
					s,
					"SELECT L.TICKET, L.LINE, L.PRODUCT, L.ATTRIBUTESETINSTANCE_ID, L.UNITS, L.PRICE, T.ID, T.NAME, T.CATEGORY, T.VALIDFROM, T.CUSTCATEGORY, T.PARENTID, T.RATE, T.RATECASCADE, T.RATEORDER, L.ATTRIBUTES FROM TICKETLINES L, TAXES T WHERE L.TAXID = T.ID AND L.TICKET = ? ORDER BY L.LINE",
					SerializerWriteString.INSTANCE, new SerializerReadClass(  TicketLineInfo.class)))
					.list(ticket.getId()));
			ticket.setPayments((new PreparedSentence(
					s,
					"SELECT PAYMENT, TOTAL, TRANSID FROM PAYMENTS WHERE RECEIPT = ?",
					SerializerWriteString.INSTANCE, new SerializerReadClass(  PaymentInfoTicket.class)))
					.list(ticket.getId()));
		}
		return ticket;
	}
///AtiBrow/src_atibrow/com/openbravo/pos/forms/DataLogicSales.java  saveTicket
	public final void saveTicket(final TicketInfo ticket,final String location)
			throws BasicException {
		Transaction t = new Transaction(this.s) {

			 
			  DataLogicSales this$0;

			public Object transact() throws BasicException {
				if (ticket.getTicketId() == 0)
					switch (ticket.getTicketType()) {
					case 0: // '\0'
						ticket.setTicketId(getNextTicketIndex().intValue());
						break;

					case 1: // '\001'
						ticket.setTicketId(getNextTicketRefundIndex()
								.intValue());
						break;

					case 2: // '\002'
						ticket.setTicketId(getNextTicketPaymentIndex()
								.intValue());
						break;

					default:
						throw new BasicException();
					}
				//end if ati 
				/*
				//com.openbravo.basic.BasicException: java.sql.SQLIntegrityConstraintViolationException:
				The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or
				 unique index identified by 'SQL151222135117940' defined on 'RECEIPTS'
				 */
				
				
							
							try {
								 
							new PreparedSentence(
							s,
							"INSERT INTO RECEIPTS (ID, MONEY, DATENEW, ATTRIBUTES) VALUES (?, ?, ?, ?)",
							SerializerWriteParams.INSTANCE) .exec(new DataParams() {

					//	final _cls7 this$1;

						public void writeValues() throws BasicException {
							setString(1, ticket.getId()); //s_mid==596e7995-f04d-4def-862f-1ee43d85a6a7
							setString(2, ticket.getActiveCash());//activecash  11c326f5-8cc1-4c08-90d0-bc1befada343
							setTimestamp(3, ticket.getDate());
							try {
								ByteArrayOutputStream o = new ByteArrayOutputStream();
								Properties properties = ticket.getProperties();
								properties.storeToXML(o, "PFPOS",
										"UTF-8");
								setBytes(4, o.toByteArray());
							} catch (IOException e) {
								setBytes(4, null);
							}
						}

						 
					});
							} catch (BasicException e) {
								System.out.println("---INSERT INTO RECEIPTS  "+e.getMessage());
							}
				
				
				(new PreparedSentence(
						s,
						"INSERT INTO TICKETS (ID, TICKETTYPE, TICKETID, PERSON, CUSTOMER) VALUES (?, ?, ?, ?, ?)",
						SerializerWriteParams.INSTANCE)).exec(new DataParams() {

				//	final _cls7 this$1;

					public void writeValues() throws BasicException {
						setString(1, ticket.getId());
						setInt(2, Integer.valueOf(ticket.getTicketType()));
						setInt(3, Integer.valueOf(ticket.getTicketId()));
						setString(4, ticket.getUser().getId());
						setString(5, ticket.getCustomerId());
					}

//					{
//						this$1 = _cls7.this;
//						super();
//					}
				});
				SentenceExec ticketlineinsert = new PreparedSentence(
						s,
						"INSERT INTO TICKETLINES (TICKET, LINE, PRODUCT, ATTRIBUTESETINSTANCE_ID, UNITS, PRICE, TAXID, ATTRIBUTES) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
						SerializerWriteBuilder.INSTANCE);
				Iterator i$ = ticket.getLines().iterator();
				do {
					if (!i$.hasNext())
						break;
					TicketLineInfo l = (TicketLineInfo) i$.next();
					ticketlineinsert.exec(l);
					if (l.getProductID() != null)
						getStockDiaryInsert()
								.exec(new Object[] {
										UUID.randomUUID().toString(),
										ticket.getDate(),
										l.getMultiply() >= 0.0D ? MovementReason.OUT_SALE
												.getKey()
												: MovementReason.IN_REFUND
														.getKey(), location,
										l.getProductID(),
										l.getProductAttSetInstId(),
										new Double(-l.getMultiply()),
										new Double(l.getPrice()) });
				} while (true);
				SentenceExec paymentinsert = new PreparedSentence(
						s,
						"INSERT INTO PAYMENTS (ID, RECEIPT, PAYMENT, TOTAL, TRANSID, RETURNMSG) VALUES (?, ?, ?, ?, ?, ?)",
						SerializerWriteParams.INSTANCE);
			//	Iterator i$ = ticket.getPayments().iterator();
				do {
					if (!i$.hasNext())
						break;
					final PaymentInfo p = (PaymentInfo) i$.next();
					paymentinsert.exec(new DataParams() {

					//	final PaymentInfo val$p;
						//final _cls7 this$1;

						public void writeValues() throws BasicException {
							setString(1, UUID.randomUUID().toString());
							setString(2, ticket.getId());
							setString(3, p.getName());
							setDouble(4, Double.valueOf(p.getTotal()));
							setString(5, ticket.getTransactionID());
							setBytes(6, (byte[]) (byte[]) Formats.BYTEA
									.parseValue(ticket.getReturnMessage()));
						}

//						{
//							this$1 = _cls7.this;
//							p = paymentinfo;
//							super();
//						}
					});
					if ("debt".equals(p.getName())
							|| "debtpaid".equals(p.getName())) {
						ticket.getCustomer().updateCurDebt(
								Double.valueOf(p.getTotal()), ticket.getDate());
						getDebtUpdate().exec(new DataParams() {

						//	final _cls7 this$1;

							public void writeValues() throws BasicException {
								setDouble(1, ticket.getCustomer().getCurdebt());
								setTimestamp(2, ticket.getCustomer()
										.getCurdate());
								setString(3, ticket.getCustomer().getId());
							}

//							{
//								this$1 = _cls7.this;
//								super();
//							}
						});
					}
				} while (true);
				SentenceExec taxlinesinsert = new PreparedSentence(
						s,
						"INSERT INTO TAXLINES (ID, RECEIPT, TAXID, BASE, AMOUNT)  VALUES (?, ?, ?, ?, ?)",
						SerializerWriteParams.INSTANCE);
			    if (ticket.getTaxes() != null) {
			    	/* 367:431 */           for (final TicketTaxInfo tickettax : ticket.getTaxes()) {
			    	/* 368:432 */             taxlinesinsert.exec(new DataParams()
			    	/* 369:    */             {
			    	/* 370:    */               public void writeValues()
			    	/* 371:    */                 throws BasicException
			    	/* 372:    */               {
			    	/* 373:433 */                 setString(1, UUID.randomUUID().toString());
			    	/* 374:434 */                 setString(2,  ticket.getId());
			    	/* 375:435 */                 setString(3, tickettax.getTaxInfo().getId());
			    	/* 376:436 */                 setDouble(4, Double.valueOf(tickettax.getSubTotal()));
			    	/* 377:437 */                 setDouble(5, Double.valueOf(tickettax.getTax()));
			    	/* 378:    */               }
			    	/* 379:    */             });
			    	/* 380:    */           }
			    	/* 381:    */         }
				return null;
			}

//			{
//				this$0 = DataLogicSales.this;
//				ticket = ticketinfo;
//				location = s1;
//				super(x0);
//			}
		};
		t.execute();
	}

	public final void deleteTicket(final TicketInfo ticket, final String location)
			throws BasicException {
		Transaction t = new Transaction(this.s) {

//			final TicketInfo val$ticket;
//			final String val$location;
//			final DataLogicSales this$0;

			public Object transact() throws BasicException {
				Date d = new Date();
				for (int i = 0; i < ticket.getLinesCount(); i++)
					if (ticket.getLine(i).getProductID() != null)
						getStockDiaryInsert()
								.exec(new Object[] {
										UUID.randomUUID().toString(),
										d,
										ticket.getLine(i).getMultiply() < 0.0D ? MovementReason.OUT_SALE
												.getKey()
												: MovementReason.IN_REFUND
														.getKey(),
										location,
										ticket.getLine(i).getProductID(),
										ticket.getLine(i)
												.getProductAttSetInstId(),
										new Double(ticket.getLine(i)
												.getMultiply()),
										new Double(ticket.getLine(i).getPrice()) });

				Iterator i$ = ticket.getPayments().iterator();
				do {
					if (!i$.hasNext())
						break;
					PaymentInfo p = (PaymentInfo) i$.next();
					if ("debt".equals(p.getName())
							|| "debtpaid".equals(p.getName())) {
						ticket.getCustomer()
								.updateCurDebt(Double.valueOf(-p.getTotal()),
										ticket.getDate());
						getDebtUpdate().exec(new DataParams() {

						//	final _cls8 this$1;

							public void writeValues() throws BasicException {
								setDouble(1, ticket.getCustomer().getCurdebt());
								setTimestamp(2, ticket.getCustomer()
										.getCurdate());
								setString(3, ticket.getCustomer().getId());
							}

//							{
//								this$1 = _cls8.this;
//								super();
//							}
						});
					}
				} while (true);
				(new StaticSentence(s,
						"DELETE FROM TAXLINES WHERE RECEIPT = ?",
						SerializerWriteString.INSTANCE)).exec(ticket.getId());
				(new StaticSentence(s,
						"DELETE FROM PAYMENTS WHERE RECEIPT = ?",
						SerializerWriteString.INSTANCE)).exec(ticket.getId());
				(new StaticSentence(s,
						"DELETE FROM TICKETLINES WHERE TICKET = ?",
						SerializerWriteString.INSTANCE)).exec(ticket.getId());
				(new StaticSentence(s, "DELETE FROM TICKETS WHERE ID = ?",
						SerializerWriteString.INSTANCE)).exec(ticket.getId());
				(new StaticSentence(s, "DELETE FROM RECEIPTS WHERE ID = ?",
						SerializerWriteString.INSTANCE)).exec(ticket.getId());
				return null;
			}

//			{
//				this$0 = DataLogicSales.this;
//				ticket = ticketinfo;
//				location = s1;
//				super(x0);
//			}
		};
		t.execute();
	}

	public final Integer getNextTicketIndex() throws BasicException {
		return (Integer) s.DB.getSequenceSentence(s, "TICKETSNUM").find();
	}

	public final Integer getNextTicketRefundIndex() throws BasicException {
		return (Integer) s.DB.getSequenceSentence(s, "TICKETSNUM_REFUND")
				.find();
	}

	public final Integer getNextTicketPaymentIndex() throws BasicException {
		return (Integer) s.DB.getSequenceSentence(s, "TICKETSNUM_PAYMENT")
				.find();
	}

	public final SentenceList getProductCatQBF() {
		return new StaticSentence(
				s,
				new QBFBuilder(
						(new StringBuilder())
								.append("SELECT P.ID, P.REFERENCE, P.CODE, P.NAME, P.ISCOM, P.ISSCALE, P.PRICEBUY, P.PRICESELL, P.CATEGORY, P.TAXCAT, P.ATTRIBUTESET_ID, P.IMAGE, P.STOCKCOST, P.STOCKVOLUME, CASE WHEN C.PRODUCT IS NULL THEN ")
								.append(s.DB.FALSE())
								.append(" ELSE ")
								.append(s.DB.TRUE())
								.append(" END, C.CATORDER, P.ATTRIBUTES ")
								.append("FROM PRODUCTS P LEFT OUTER JOIN PRODUCTS_CAT C ON P.ID = C.PRODUCT ")
								.append("WHERE ?(QBF_FILTER) ")
								.append("ORDER BY P.REFERENCE").toString(),
						new String[] { "P.NAME", "P.PRICEBUY", "P.PRICESELL",
								"P.CATEGORY", "P.CODE" }),
				new SerializerWriteBasic(new Datas[] { Datas.OBJECT,
						Datas.STRING, Datas.OBJECT, Datas.DOUBLE, Datas.OBJECT,
						Datas.DOUBLE, Datas.OBJECT, Datas.STRING, Datas.OBJECT,
						Datas.STRING }), productsRow.getSerializerRead());
	}

	public final SentenceExec getProductCatInsert() {
		return new SentenceExecTransaction(s) {

		//	final DataLogicSales this$0;

			public int execInTransaction(Object params) throws BasicException {
				Object values[] = (Object[]) (Object[]) params;
				int i = (new PreparedSentence(
						s,
						"INSERT INTO PRODUCTS (ID, REFERENCE, CODE, NAME, ISCOM, ISSCALE, PRICEBUY, PRICESELL, CATEGORY, TAXCAT, ATTRIBUTESET_ID, IMAGE, STOCKCOST, STOCKVOLUME, ATTRIBUTES) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
						new SerializerWriteBasicExt(productsRow.getDatas(),
								new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
										11, 12, 13, 16 }))).exec(params);
				if (i > 0 && ((Boolean) values[14]).booleanValue())
					return (new PreparedSentence(
							s,
							"INSERT INTO PRODUCTS_CAT (PRODUCT, CATORDER) VALUES (?, ?)",
							new SerializerWriteBasicExt(productsRow.getDatas(),
									new int[] { 0, 15 }))).exec(params);
				else
					return i;
			}

//			{
//				this$0 = DataLogicSales.this;
//				super(x0);
//			}
		};
	}

	public final SentenceExec getProductCatUpdate() {
		return new SentenceExecTransaction(s) {

		//	final DataLogicSales this$0;

			public int execInTransaction(Object params) throws BasicException {
				Object values[] = (Object[]) (Object[]) params;
				int i = (new PreparedSentence(
						s,
						"UPDATE PRODUCTS SET ID = ?, REFERENCE = ?, CODE = ?, NAME = ?, ISCOM = ?, ISSCALE = ?, PRICEBUY = ?, PRICESELL = ?, CATEGORY = ?, TAXCAT = ?, ATTRIBUTESET_ID = ?, IMAGE = ?, STOCKCOST = ?, STOCKVOLUME = ?, ATTRIBUTES = ? WHERE ID = ?",
						new SerializerWriteBasicExt(productsRow.getDatas(),
								new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
										11, 12, 13, 16, 0 }))).exec(params);
				if (i > 0)
					if (((Boolean) values[14]).booleanValue()) {
						if ((new PreparedSentence(
								s,
								"UPDATE PRODUCTS_CAT SET CATORDER = ? WHERE PRODUCT = ?",
								new SerializerWriteBasicExt(productsRow
										.getDatas(), new int[] { 15, 0 })))
								.exec(params) == 0)
							(new PreparedSentence(
									s,
									"INSERT INTO PRODUCTS_CAT (PRODUCT, CATORDER) VALUES (?, ?)",
									new SerializerWriteBasicExt(productsRow
											.getDatas(), new int[] { 0, 15 })))
									.exec(params);
					} else {
						(new PreparedSentence(s,
								"DELETE FROM PRODUCTS_CAT WHERE PRODUCT = ?",
								new SerializerWriteBasicExt(productsRow
										.getDatas(), new int[] { 0 })))
								.exec(params);
					}
				return i;
			}

//			{
//				this$0 = DataLogicSales.this;
//				super(x0);
//			}
		};
	}

	public final SentenceExec getProductCatDelete() {
		return new SentenceExecTransaction(s) {

		//	final DataLogicSales this$0;

			public int execInTransaction(Object params) throws BasicException {
				(new PreparedSentence(s,
						"DELETE FROM PRODUCTS_CAT WHERE PRODUCT = ?",
						new SerializerWriteBasicExt(productsRow.getDatas(),
								new int[] { 0 }))).exec(params);
				return (new PreparedSentence(s,
						"DELETE FROM PRODUCTS WHERE ID = ?",
						new SerializerWriteBasicExt(productsRow.getDatas(),
								new int[] { 0 }))).exec(params);
			}
//
//			{
//				this$0 = DataLogicSales.this;
//				super(x0);
//			}
		};
	}

	public final SentenceExec getDebtUpdate() {
		return new PreparedSentence(s,
				"UPDATE CUSTOMERS SET CURDEBT = ?, CURDATE = ? WHERE ID = ?",
				SerializerWriteParams.INSTANCE);
	}

	public final SentenceExec getStockDiaryInsert() {
		return new SentenceExecTransaction(s) {

			//final DataLogicSales this$0;

			public int execInTransaction(Object params) throws BasicException {
				int updateresult = ((Object[]) (Object[]) params)[5] != null ? (new PreparedSentence(
						s,
						"UPDATE STOCKCURRENT SET UNITS = (UNITS + ?) WHERE LOCATION = ? AND PRODUCT = ? AND ATTRIBUTESETINSTANCE_ID = ?",
						new SerializerWriteBasicExt(stockdiaryDatas, new int[] {
								6, 3, 4, 5 }))).exec(params)
						: (new PreparedSentence(
								s,
								"UPDATE STOCKCURRENT SET UNITS = (UNITS + ?) WHERE LOCATION = ? AND PRODUCT = ? AND ATTRIBUTESETINSTANCE_ID IS NULL",
								new SerializerWriteBasicExt(stockdiaryDatas,
										new int[] { 6, 3, 4 }))).exec(params);
				if (updateresult == 0)
					(new PreparedSentence(
							s,
							"INSERT INTO STOCKCURRENT (LOCATION, PRODUCT, ATTRIBUTESETINSTANCE_ID, UNITS) VALUES (?, ?, ?, ?)",
							new SerializerWriteBasicExt(stockdiaryDatas,
									new int[] { 3, 4, 5, 6 }))).exec(params);
				return (new PreparedSentence(
						s,
						"INSERT INTO STOCKDIARY (ID, DATENEW, REASON, LOCATION, PRODUCT, ATTRIBUTESETINSTANCE_ID, UNITS, PRICE) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
						new SerializerWriteBasicExt(stockdiaryDatas, new int[] {
								0, 1, 2, 3, 4, 5, 6, 7 }))).exec(params);
			}

//			{
//				this$0 = DataLogicSales.this;
//				super(x0);
//			}
		};
	}

	public final SentenceExec getStockDiaryDelete() {
		return new SentenceExecTransaction(s) {

		//	final DataLogicSales this$0;

			public int execInTransaction(Object params) throws BasicException {
				int updateresult = ((Object[]) (Object[]) params)[5] != null ? (new PreparedSentence(
						s,
						"UPDATE STOCKCURRENT SET UNITS = (UNITS - ?) WHERE LOCATION = ? AND PRODUCT = ? AND ATTRIBUTESETINSTANCE_ID = ?",
						new SerializerWriteBasicExt(stockdiaryDatas, new int[] {
								6, 3, 4, 5 }))).exec(params)
						: (new PreparedSentence(
								s,
								"UPDATE STOCKCURRENT SET UNITS = (UNITS - ?) WHERE LOCATION = ? AND PRODUCT = ? AND ATTRIBUTESETINSTANCE_ID IS NULL",
								new SerializerWriteBasicExt(stockdiaryDatas,
										new int[] { 6, 3, 4 }))).exec(params);
				if (updateresult == 0)
					(new PreparedSentence(
							s,
							"INSERT INTO STOCKCURRENT (LOCATION, PRODUCT, ATTRIBUTESETINSTANCE_ID, UNITS) VALUES (?, ?, ?, -(?))",
							new SerializerWriteBasicExt(stockdiaryDatas,
									new int[] { 3, 4, 5, 6 }))).exec(params);
				return (new PreparedSentence(s,
						"DELETE FROM STOCKDIARY WHERE ID = ?",
						new SerializerWriteBasicExt(stockdiaryDatas,
								new int[] { 0 }))).exec(params);
			}

//			{
//				this$0 = DataLogicSales.this;
//				super(x0);
//			}
		};
	}

	public final SentenceExec getPaymentMovementInsert() {
		return new SentenceExecTransaction(s) {

			//final DataLogicSales this$0;

			public int execInTransaction(Object params) throws BasicException {
				(new PreparedSentence(
						s,
						"INSERT INTO RECEIPTS (ID, MONEY, DATENEW) VALUES (?, ?, ?)",
						new SerializerWriteBasicExt(paymenttabledatas,
								new int[] { 0, 1, 2 }))).exec(params);
				return (new PreparedSentence(
						s,
						"INSERT INTO PAYMENTS (ID, RECEIPT, PAYMENT, TOTAL) VALUES (?, ?, ?, ?)",
						new SerializerWriteBasicExt(paymenttabledatas,
								new int[] { 3, 0, 4, 5 }))).exec(params);
			}

//			{
//				this$0 = DataLogicSales.this;
//				super(x0);
//			}
		};
	}

	public final SentenceExec getPaymentMovementDelete() {
		return new SentenceExecTransaction(s) {

		//	final DataLogicSales this$0;

			public int execInTransaction(Object params) throws BasicException {
				(new PreparedSentence(s, "DELETE FROM PAYMENTS WHERE ID = ?",
						new SerializerWriteBasicExt(paymenttabledatas,
								new int[] { 3 }))).exec(params);
				return (new PreparedSentence(s,
						"DELETE FROM RECEIPTS WHERE ID = ?",
						new SerializerWriteBasicExt(paymenttabledatas,
								new int[] { 0 }))).exec(params);
			}

//			{
//				this$0 = DataLogicSales.this;
//				super(x0);
//			}
		};
	}

	public final double findProductStock(String warehouse, String id,
			String attsetinstid) throws BasicException {
		PreparedSentence p = attsetinstid != null ? new PreparedSentence(
				s,
				"SELECT UNITS FROM STOCKCURRENT WHERE LOCATION = ? AND PRODUCT = ? AND ATTRIBUTESETINSTANCE_ID = ?",
				new SerializerWriteBasic(new Datas[] { Datas.STRING,
						Datas.STRING, Datas.STRING }),
				SerializerReadDouble.INSTANCE)
				: new PreparedSentence(
						s,
						"SELECT UNITS FROM STOCKCURRENT WHERE LOCATION = ? AND PRODUCT = ? AND ATTRIBUTESETINSTANCE_ID IS NULL",
						new SerializerWriteBasic(new Datas[] { Datas.STRING,
								Datas.STRING }), SerializerReadDouble.INSTANCE);
		Double d = (Double) p
				.find(new Object[] { warehouse, id, attsetinstid });
		return d != null ? d.doubleValue() : 0.0D;
	}

	public final SentenceExec getCatalogCategoryAdd() {
		return new StaticSentence(
				s,
				(new StringBuilder())
						.append("INSERT INTO PRODUCTS_CAT(PRODUCT, CATORDER) SELECT ID, ")
						.append(s.DB.INTEGER_NULL())
						.append(" FROM PRODUCTS WHERE CATEGORY = ?").toString(),
				SerializerWriteString.INSTANCE);
	}

	public final SentenceExec getCatalogCategoryDel() {
		return new StaticSentence(
				s,
				"DELETE FROM PRODUCTS_CAT WHERE PRODUCT = ANY (SELECT ID FROM PRODUCTS WHERE CATEGORY = ?)",
				SerializerWriteString.INSTANCE);
	}

	public final TableDefinition getTableCategories() {
		return new TableDefinition(s, "CATEGORIES", new String[] { "ID",
				"NAME", "PARENTID", "IMAGE" }, new String[] { "ID",
				AppLocal.getIntString("Label.Name"), "",
				AppLocal.getIntString("label.image") }, new Datas[] {
				Datas.STRING, Datas.STRING, Datas.STRING, Datas.IMAGE },
				new Formats[] { Formats.STRING, Formats.STRING, Formats.STRING,
						Formats.NULL }, new int[] { 0 });
	}

	public final TableDefinition getTableTaxes() {
		return new TableDefinition(s, "TAXES", new String[] { "ID", "NAME",
				"CATEGORY", "VALIDFROM", "CUSTCATEGORY", "PARENTID", "RATE",
				"RATECASCADE", "RATEORDER" }, new String[] { "ID",
				AppLocal.getIntString("Label.Name"),
				AppLocal.getIntString("label.taxcategory"),
				AppLocal.getIntString("Label.ValidFrom"),
				AppLocal.getIntString("label.custtaxcategory"),
				AppLocal.getIntString("label.taxparent"),
				AppLocal.getIntString("label.dutyrate"),
				AppLocal.getIntString("label.cascade"),
				AppLocal.getIntString("label.order") }, new Datas[] {
				Datas.STRING, Datas.STRING, Datas.STRING, Datas.TIMESTAMP,
				Datas.STRING, Datas.STRING, Datas.DOUBLE, Datas.BOOLEAN,
				Datas.INT },
				new Formats[] { Formats.STRING, Formats.STRING, Formats.STRING,
						Formats.TIMESTAMP, Formats.STRING, Formats.STRING,
						Formats.PERCENT, Formats.BOOLEAN, Formats.INT },
				new int[] { 0 });
	}

	public final TableDefinition getTableTaxCustCategories() {
		return new TableDefinition(s, "TAXCUSTCATEGORIES", new String[] { "ID",
				"NAME" }, new String[] { "ID",
				AppLocal.getIntString("Label.Name") }, new Datas[] {
				Datas.STRING, Datas.STRING }, new Formats[] { Formats.STRING,
				Formats.STRING }, new int[] { 0 });
	}

	public final TableDefinition getTableTaxCategories() {
		return new TableDefinition(s, "TAXCATEGORIES", new String[] { "ID",
				"NAME" }, new String[] { "ID",
				AppLocal.getIntString("Label.Name") }, new Datas[] {
				Datas.STRING, Datas.STRING }, new Formats[] { Formats.STRING,
				Formats.STRING }, new int[] { 0 });
	}

	public final TableDefinition getTableLocations() {
		return new TableDefinition(s, "LOCATIONS", new String[] { "ID", "NAME",
				"ADDRESS" }, new String[] { "ID",
				AppLocal.getIntString("label.locationname"),
				AppLocal.getIntString("label.locationaddress") }, new Datas[] {
				Datas.STRING, Datas.STRING, Datas.STRING }, new Formats[] {
				Formats.STRING, Formats.STRING, Formats.STRING },
				new int[] { 0 });
	}
}
